/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.uml_generator.manager.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.genia.toolbox.basics.bean.DisplayObject;
import com.genia.toolbox.basics.bean.impl.ConstantDelimiter;
import com.genia.toolbox.basics.exception.BundledException;
import com.genia.toolbox.basics.exception.technical.TechnicalIOException;
import com.genia.toolbox.uml_generator.Constants;
import com.genia.toolbox.uml_generator.bean.ModelGeneratorContext;
import com.genia.toolbox.uml_generator.manager.PrinterManager;
import com.genia.toolbox.uml_generator.model.AbstractClassModel;
import com.genia.toolbox.uml_generator.model.AbstractDelegatableObject;
import com.genia.toolbox.uml_generator.model.AbstractJavaObject;
import com.genia.toolbox.uml_generator.model.AttributeModel;
import com.genia.toolbox.uml_generator.model.OperationModel;

/**
 * implementation of {@link PrinterManager}.
 */
public class PrinterManagerImpl
    extends AbstractManager
    implements PrinterManager
{

  /**
   * print an {@link AttributeModel}.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param out
   *          the {@link Appendable} to print to
   * @param attribute
   *          the attribute to write
   * @return the {@link Appendable} that has been print to
   * @throws TechnicalIOException
   *           when an I/O error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printAttribute(java.lang.Appendable,
   *      com.genia.toolbox.uml_generator.model.AttributeModel)
   */
  public <T extends Appendable> T printAttribute(T out, AttributeModel attribute)
      throws TechnicalIOException
  {
    try {
      printSignature(out, attribute).append(" = ").append(attribute.getInitialValue()).append(";\n");
    }
    catch (IOException e) {
      throw getExceptionManager().convertException(e);
    }
    return out;
  }



  /**
   * print javadoc comment.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param out
   *          the {@link Appendable} to print to
   * @param comments
   *          the comments to print.
   * @return the {@link Appendable} that has been print to
   * @throws TechnicalIOException
   *           when an error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printComment(java.lang.Appendable,
   *      java.lang.String[])
   */
  public <T extends Appendable> T printComment(T out, String... comments)
      throws TechnicalIOException
  {
    try {
      out.append("/**").append("\n");
      for (String comment : comments) {
        out.append(" * ").append(comment).append("\n");
      }
      out.append(" */").append("\n");
    }
    catch (IOException e) {
      throw getExceptionManager().convertException(e);
    }
    return out;
  }



  /**
   * print the declaration of an {@link AttributeModel}.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param out
   *          the {@link Appendable} to print to
   * @param attribute
   *          the attribute to write the declaration for
   * @return the {@link Appendable} that has been print to
   * @throws TechnicalIOException
   *           when an I/O error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printDeclaration(java.lang.Appendable,
   *      com.genia.toolbox.uml_generator.model.AttributeModel)
   */
  public <T extends Appendable> T printDeclaration(T out, AttributeModel attribute)
      throws TechnicalIOException
  {
    try {
      printSignature(out, attribute).append(";\n");
    }
    catch (IOException e) {
      throw getExceptionManager().convertException(e);
    }
    return out;
  }



  /**
   * print the declaration of an {@link OperationModel}.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param out
   *          the {@link Appendable} to print to
   * @param operation
   *          the operation to write the declaration for
   * @return the {@link Appendable} that has been print to
   * @throws TechnicalIOException
   *           when an I/O error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printDeclaration(java.lang.Appendable,
   *      com.genia.toolbox.uml_generator.model.OperationModel)
   */
  public <T extends Appendable> T printDeclaration(T out, OperationModel operation)
      throws TechnicalIOException
  {
    try {
      printSignature(out, operation).append(";");
    }
    catch (IOException e) {
      throw new TechnicalIOException(e);
    }
    return out;
  }



  /**
   * print the dependencies.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param context
   *          the context of the generation
   * @param out
   *          the {@link Appendable} to print to
   * @param object
   *          the object being printed
   * @param otherInterfaces
   *          the other interfaces the object must implement
   * @return the {@link Appendable} that has been print to
   * @throws BundledException
   *           when an error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printDependencies(java.lang.Appendable,
   *      java.lang.String,
   *      com.genia.toolbox.uml_generator.model.AbstractDelegatableObject)
   */
  public <T extends Appendable> T printDependencies(ModelGeneratorContext context, T out, AbstractDelegatableObject object, AbstractJavaObject... otherInterfaces)
      throws BundledException
  {
    try {
      String dependencyKeyword = Constants.IMPLEMENTS_RESERVED_WORD;
      Set<AbstractJavaObject> models = getCollectionManager().filterCollection(new HashSet<AbstractJavaObject>(), getModelInspector().findMinimumImplementationSet(object),
          Constants.IS_NOT_PERSISTABLE_INTERFACE_PREDICATE);
      if (object instanceof AbstractClassModel) {
        AbstractClassModel classModel = (AbstractClassModel) object;
        if (classModel.isInterface()) {
          dependencyKeyword = Constants.EXTENDS_RESERVED_WORD;
        }
        else {
          if (classModel.getParent() != null) {
            out.append(Constants.EXTENDS_RESERVED_WORD).append(" ").append(object.getParent().getQualifiedName()).append(" ");
          }
          if (getModelInspector().isFirstPersistable(object)) {
            AttributeModel objectIdentifier = getModelInspector().getIdentifier((AbstractClassModel) object);
            if (objectIdentifier == null) {
              throw new TechnicalIOException(new IOException("Class " + object.getQualifiedName() + " is persistable but has no identifier."));
            }
            models.add(getModelDecorator().getGenericObject(getModelInspector().getPersistableModel(context), objectIdentifier.getType()));
          }
        }
      }
      models.addAll(Arrays.asList(otherInterfaces));
      if (!models.isEmpty()) {
        getCollectionManager().join(out, models, new ConstantDelimiter(dependencyKeyword + " ", ",", ""), new DisplayObject<AbstractJavaObject>()
        {
          public void append(Appendable appendable, AbstractJavaObject object)
              throws IOException
          {
            appendable.append(object.getQualifiedName());
          }
        });
      }
    }
    catch (IOException e) {
      throw getExceptionManager().convertException(e);
    }
    return out;
  }



  /**
   * print an {@link OperationModel}.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param out
   *          the {@link Appendable} to print to
   * @param operation
   *          the operation to writer
   * @return the {@link Appendable} that has been print to
   * @throws TechnicalIOException
   *           when an I/O error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printMethod(java.lang.Appendable,
   *      com.genia.toolbox.uml_generator.model.OperationModel)
   */
  public <T extends Appendable> T printMethod(T out, OperationModel operation)
      throws TechnicalIOException
  {
    try {
      printSignature(out, operation).append("\n{\n").append(operation.getBody()).append("\n}\n");
    }
    catch (IOException e) {
      throw new TechnicalIOException(e);
    }
    return out;
  }



  /**
   * print the package declaration.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param out
   *          the {@link Appendable} to print to
   * @param object
   *          the object being printed
   * @return the {@link Appendable} that has been print to
   * @throws TechnicalIOException
   *           when an I/O error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printPackage(java.lang.Appendable,
   *      com.genia.toolbox.uml_generator.model.AbstractJavaObject)
   */
  public <T extends Appendable> T printPackage(T out, AbstractJavaObject object)
      throws TechnicalIOException
  {
    try {
      out.append("package ").append(object.getPackageName()).append(";").append("\n");
    }
    catch (IOException e) {
      throw getExceptionManager().convertException(e);
    }
    return out;
  }



  /**
   * print the signature of an {@link AttributeModel}.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param out
   *          the {@link Appendable} to print to
   * @param attribute
   *          the attribute to write the signature for
   * @return the {@link Appendable} that has been print to
   * @throws TechnicalIOException
   *           when an I/O error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printSignature(java.lang.Appendable,
   *      com.genia.toolbox.uml_generator.model.AttributeModel)
   */
  public <T extends Appendable> T printSignature(T out, AttributeModel attribute)
      throws TechnicalIOException
  {
    printComment(out, attribute.getComment());
    try {
      out.append("private ").append(attribute.getType().getQualifiedName()).append(" ").append(attribute.getName());
    }
    catch (IOException e) {
      throw getExceptionManager().convertException(e);
    }
    return out;
  }



  /**
   * print the signature of an {@link OperationModel}.
   * 
   * @param <T>
   *          the type of the {@link Appendable}
   * @param out
   *          the {@link Appendable} to print to
   * @param operation
   *          the operation to write the signature for
   * @return the {@link Appendable} that has been print to
   * @throws TechnicalIOException
   *           when an I/O error occurred
   * @see com.genia.toolbox.uml_generator.manager.PrinterManager#printDeclaration(java.lang.Appendable,
   *      com.genia.toolbox.uml_generator.model.OperationModel)
   */
  public <T extends Appendable> T printSignature(T out, OperationModel operation)
      throws TechnicalIOException
  {

    // Handle comments.
    List<String> comments = new ArrayList<String>();
    comments.add(operation.getComment());
    for (AttributeModel parameter : operation.getParameterModels()) {
      comments.add("@param " + parameter.getName() + " " + parameter.getComment());
    }
    if (!operation.hasVoidReturnType()) {
      comments.add("@return " + operation.getReturnType().getComment());
    }
    printComment(out, comments.toArray(new String[comments.size()]));

    // Handle declaration.
    try {
      if (operation.isOverride()) {
        out.append("@Override\n");
      }
      out.append("public ").append(operation.getReturnType().getType().getQualifiedName()).append(" ").append(operation.getName());
      getCollectionManager().join(out, operation.getParameterModels(), new ConstantDelimiter("(", ",", ")"), new DisplayObject<AttributeModel>()
      {

        public void append(Appendable appendable, AttributeModel object)
            throws IOException
        {
          appendable.append(object.getType().getQualifiedName()).append(" ").append(object.getName());
        }
      });
    }
    catch (IOException e) {
      throw new TechnicalIOException(e);
    }
    return out;
  }

}
